package com.quick.calcu.service;

import com.quick.calcu.entity.Student;
import com.quick.calcu.entity.Teacher;
import com.quick.calcu.entity.User;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RegisterService {
    @Autowired
    private UserService userService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @Transactional
    public boolean registerWithRole(User user) {
        // 检查用户名是否已存在
        if (userService.existsByUsername(user.getUsername())) {
            return false;
        }

        boolean userSaved = userService.save(user);
        if (!userSaved) {
            throw new RuntimeException("用户保存失败");
        }

        if (user.getUserType() == 1) {
            Student student = new Student();
            student.setUserId(user.getUserId());
            student.setStudentName(user.getUsername());
            if (!studentService.save(student)) {
                return false;
//                throw new RuntimeException("学生信息保存失败");
            }
        } else if (user.getUserType() == 2) {
            Teacher teacher = new Teacher();
            teacher.setUserId(user.getUserId());
            teacher.setTeacherName(user.getUsername());
            if (!teacherService.save(teacher)) {
                return false;
//                throw new RuntimeException("教师信息保存失败");
            }
        } else {
            return false;
//            throw new RuntimeException("不支持的用户类型");
        }

        return true;
    }
}
